package br.edu.ufcg.ga.output;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import br.edu.ufcg.ga.CaixeiroViajante;

public class FullOutputGenerator extends MainRunOutputGenerator {

	private static final String LINE_SEPARATOR = System.getProperty("line.separator");

	@Override
	public void generateOutput(double bestFitnessValue, CaixeiroViajante cv) throws Exception {
		long seed = cv.getRandom().getSeed();
		generateGenerationsOutput(cv, seed);
		generateGeneralOutput(bestFitnessValue, cv, seed);
	}

	private void generateGenerationsOutput(CaixeiroViajante cv, long seed) throws IOException {
		StringBuilder sb = new StringBuilder();

		List<Double> bestFitnessValues = cv.getOutputInfo().getBestFitnessValues();
		if (bestFitnessValues != null) {

			for (Double value : bestFitnessValues) {
				sb.append(value);
				sb.append(LINE_SEPARATOR);
			}

			writeToFile("generations_and_fittest-" + seed + ".out", sb.toString());
		}

	}

	protected void writeGeneralOutput(String content, long seed) throws Exception {
		writeToFile("output-" + seed + ".out", content + LINE_SEPARATOR);
	}
	
	private void writeToFile(String fileName, String content) throws IOException {
		BufferedWriter bw = null;

		try {
			bw = new BufferedWriter(new FileWriter(new File(fileName)));
			bw.write(content);
		} finally {
			if (bw != null) {
				bw.close();
			}
		}
	}

}
